<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Toast, Dialog } from 'vant'
import api from '@/api'

const route = useRoute()
const router = useRouter()
const brandName = route.query.brand

// 产品详情
const productInfo = ref({
  id: 1,
  name: brandName || 'ZG-ONE',
  price: 1000,
  minInvestment: 100,
  totalShares: 10000,
  soldShares: 5600,
  shareholders: 3761,
  description: '这是一款专为低空旅游设计的轻型飞机，采用先进的复合材料制造，具有出色的安全性能和飞行体验。参与品牌共建，共享品牌收益，成为航空产业的一份子。',
  features: [
    '最大起飞重量：600kg',
    '巡航速度：180km/h',
    '航程：500km',
    '座位数：2人',
    '发动机：Rotax 912',
    '油耗：15L/h'
  ],
  images: [
    'https://pan.feiwow.com/raw/files/17b90398-8f34-4509-952d-79cb8dbdff07-1749241617399.png',
    'https://pan.feiwow.com/raw/files/9f8e76e6-3aed-41e0-bb68-ac8c995abfbe-1749241924810.png',
    'https://pan.feiwow.com/raw/files/0918b246-4f79-4516-b300-dd70ddbb7834-1749241488302.jpeg'
  ],
  video: 'https://pan.feiwow.com/raw/files/17b90398-8f34-4509-952d-79cb8dbdff07-1749241617399.png'
})

// 当前轮次信息
const currentRound = ref({
  name: '第一轮融资',
  target: 500000,
  current: 280000,
  deadline: '2023-12-31',
  remainingDays: 45
})

// 投资档位
const investmentOptions = reactive([
  { id: 1, amount: 100, shares: 1, benefits: ['基础股东权益', '年度分红'] },
  { id: 2, amount: 500, shares: 5, benefits: ['基础股东权益', '年度分红', '专属纪念品'] },
  { id: 3, amount: 1000, shares: 10, benefits: ['基础股东权益', '年度分红', '专属纪念品', '优先试飞权'] },
  { id: 4, amount: 5000, shares: 50, benefits: ['全部股东权益', 'VIP身份标识', '专属客服'] }
])

// 投资人评价
const reviews = reactive([
  {
    id: 1,
    username: '航空爱好者',
    avatar: 'https://picsum.photos/200/200?random=1',
    content: '非常看好这个项目，低空旅游市场潜力巨大，投资了1000元，期待未来的发展！',
    time: '2023-10-10',
    rating: 5
  },
  {
    id: 2,
    username: '理财达人',
    avatar: 'https://picsum.photos/200/200?random=2',
    content: '项目团队非常专业，对航空产业有深入了解，产品设计也很有竞争力。',
    time: '2023-10-08',
    rating: 4
  },
  {
    id: 3,
    username: '新手投资者',
    avatar: 'https://picsum.photos/200/200?random=3',
    content: '第一次参与这类投资项目，操作流程很简单，客服解答也很及时。',
    time: '2023-10-05',
    rating: 5
  }
])

// 当前选中的投资选项
const selectedOption = ref(null)
// 当前轮次进度百分比
const roundProgress = computed(() => {
  return (currentRound.value.current / currentRound.value.target) * 100
})
// 当前展示的图片索引
const currentImageIndex = ref(0)

// 页面加载完成后初始化
onMounted(() => {
  loadProductInfo()
  loadCurrentRound()
  loadInvestmentOptions()
  loadReviews()
})

// 加载产品详情
const loadProductInfo = async () => {
  try {
    // 实际项目中应该从API获取数据
    // const response = await api.airplane.getProductInfo(brandName)
    // productInfo.value = response.data
    console.log('加载产品详情:', brandName)
  } catch (error) {
    console.error('加载产品详情失败:', error)
    Toast.fail('加载产品详情失败')
  }
}

// 加载当前轮次信息
const loadCurrentRound = async () => {
  try {
    // 实际项目中应该从API获取数据
    // const response = await api.airplane.getCurrentRound(brandName)
    // currentRound.value = response.data
    console.log('加载当前轮次信息')
  } catch (error) {
    console.error('加载当前轮次信息失败:', error)
  }
}

// 加载投资选项
const loadInvestmentOptions = async () => {
  try {
    // 实际项目中应该从API获取数据
    // const response = await api.airplane.getInvestmentOptions(brandName)
    // investmentOptions.value = response.data
    console.log('加载投资选项')
  } catch (error) {
    console.error('加载投资选项失败:', error)
  }
}

// 加载评价
const loadReviews = async () => {
  try {
    // 实际项目中应该从API获取数据
    // const response = await api.airplane.getReviews(brandName)
    // reviews.value = response.data
    console.log('加载评价')
  } catch (error) {
    console.error('加载评价失败:', error)
  }
}

// 选择投资选项
const selectOption = (option) => {
  selectedOption.value = option
}

// 处理投资
const handleInvest = () => {
  if (!selectedOption.value) {
    Toast.fail('请选择投资档位')
    return
  }
  
  Dialog.confirm({
    title: '确认投资',
    message: `您确定要投资${selectedOption.value.amount}元，购买${selectedOption.value.shares}股吗？`,
    confirmButtonText: '确认投资',
    cancelButtonText: '再想想'
  }).then(() => {
    // 实际项目中应该调用API
    // await api.airplane.invest(productInfo.value.id, selectedOption.value.id)
    Toast.success('投资功能开发中')
  }).catch(() => {
    // 用户取消
  })
}

// 切换图片
const changeImage = (index) => {
  currentImageIndex.value = index
}

// 播放视频
const playVideo = () => {
  Toast.success('视频播放功能开发中')
}

// 分享项目
const shareProject = () => {
  Toast.success('分享功能开发中')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 格式化金额
const formatAmount = (amount) => {
  return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
</script>

<template>
  <div class="page-container">
    <!-- 顶部导航栏 -->
    <div class="navbar">
      <div class="back-btn" @click="goBack">
        <van-icon name="arrow-left" />
      </div>
      <div class="nav-title">{{ productInfo.name }}</div>
      <div class="share-btn" @click="shareProject">
        <van-icon name="share-o" />
      </div>
    </div>
    
    <!-- 产品图片轮播 -->
    <div class="product-images">
      <img :src="productInfo.images[currentImageIndex]" :alt="productInfo.name" class="main-image">
      <div class="image-thumbnails">
        <div 
          v-for="(image, index) in productInfo.images" 
          :key="index" 
          class="thumbnail"
          :class="{ active: currentImageIndex === index }"
          @click="changeImage(index)"
        >
          <img :src="image" :alt="`缩略图${index + 1}`">
        </div>
        <div class="thumbnail video" @click="playVideo">
          <img :src="productInfo.video" alt="视频封面">
          <div class="video-play-icon">
            <van-icon name="play-circle-o" />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 产品信息 -->
    <div class="product-info">
      <div class="product-name">{{ productInfo.name }}</div>
      <div class="product-price">
        <span class="label">起投金额：</span>
        <span class="price">¥{{ productInfo.minInvestment }}</span>
      </div>
      <div class="product-stats">
        <div class="stat-item">
          <div class="stat-value">{{ productInfo.shareholders }}</div>
          <div class="stat-label">参与股东</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ productInfo.soldShares }}/{{ productInfo.totalShares }}</div>
          <div class="stat-label">已售股份</div>
        </div>
      </div>
    </div>
    
    <!-- 当前轮次 -->
    <div class="funding-round">
      <div class="round-header">
        <div class="round-name">{{ currentRound.name }}</div>
        <div class="round-deadline">截止日期：{{ currentRound.deadline }}（剩{{ currentRound.remainingDays }}天）</div>
      </div>
      <div class="round-progress">
        <div class="progress-text">
          <span>已筹：¥{{ formatAmount(currentRound.current) }}</span>
          <span>目标：¥{{ formatAmount(currentRound.target) }}</span>
        </div>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: roundProgress + '%' }"></div>
        </div>
        <div class="progress-percent">{{ roundProgress.toFixed(1) }}%</div>
      </div>
    </div>
    
    <!-- 投资选项 -->
    <div class="investment-options">
      <div class="section-title">选择投资档位</div>
      <div class="options-list">
        <div 
          v-for="option in investmentOptions" 
          :key="option.id" 
          class="option-item"
          :class="{ selected: selectedOption && selectedOption.id === option.id }"
          @click="selectOption(option)"
        >
          <div class="option-header">
            <div class="option-amount">¥{{ option.amount }}</div>
            <div class="option-shares">{{ option.shares }}股</div>
          </div>
          <div class="option-benefits">
            <div v-for="(benefit, index) in option.benefits" :key="index" class="benefit-item">
              <van-icon name="success" />
              <span>{{ benefit }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 产品描述 -->
    <div class="product-description">
      <div class="section-title">项目介绍</div>
      <div class="description-content">{{ productInfo.description }}</div>
      <div class="product-features">
        <div v-for="(feature, index) in productInfo.features" :key="index" class="feature-item">
          <van-icon name="checked" />
          <span>{{ feature }}</span>
        </div>
      </div>
    </div>
    
    <!-- 投资人评价 -->
    <div class="reviews-section">
      <div class="section-title">投资人评价</div>
      <div class="reviews-list">
        <div v-for="review in reviews" :key="review.id" class="review-item">
          <div class="review-header">
            <img :src="review.avatar" :alt="review.username" class="review-avatar">
            <div class="review-info">
              <div class="review-username">{{ review.username }}</div>
              <div class="review-rating">
                <van-icon 
                  v-for="i in 5" 
                  :key="i" 
                  :name="i <= review.rating ? 'star' : 'star-o'" 
                  :class="{ active: i <= review.rating }"
                />
              </div>
            </div>
            <div class="review-time">{{ review.time }}</div>
          </div>
          <div class="review-content">{{ review.content }}</div>
        </div>
      </div>
    </div>
    
    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <div class="customer-service">
        <van-icon name="service-o" />
        <span>客服</span>
      </div>
      <div class="invest-btn" @click="handleInvest">立即投资</div>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 60px;
}

/* 顶部导航栏 */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: white;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn, .share-btn {
  width: 30px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.back-btn .van-icon, .share-btn .van-icon {
  font-size: 20px;
}

.nav-title {
  font-size: 16px;
  font-weight: bold;
}

/* 产品图片 */
.product-images {
  background-color: white;
  padding: 15px;
}

.main-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 10px;
}

.image-thumbnails {
  display: flex;
  overflow-x: auto;
  gap: 10px;
  padding-bottom: 5px;
}

.thumbnail {
  width: 60px;
  height: 60px;
  flex-shrink: 0;
  border-radius: 4px;
  overflow: hidden;
  border: 2px solid transparent;
  position: relative;
}

.thumbnail.active {
  border-color: var(--primary-color);
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail.video {
  position: relative;
}

.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 24px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.5);
}

/* 产品信息 */
.product-info {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.product-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.product-price {
  margin-bottom: 15px;
}

.product-price .label {
  font-size: 14px;
  color: #666;
}

.product-price .price {
  font-size: 20px;
  font-weight: bold;
  color: #FF3B30;
}

.product-stats {
  display: flex;
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

/* 当前轮次 */
.funding-round {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.round-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.round-name {
  font-size: 16px;
  font-weight: bold;
  color: var(--primary-color);
}

.round-deadline {
  font-size: 12px;
  color: #FF3B30;
}

.round-progress {
  position: relative;
}

.progress-text {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.progress-bar {
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 5px;
}

.progress-fill {
  height: 100%;
  background-color: var(--primary-color);
  border-radius: 4px;
}

.progress-percent {
  text-align: right;
  font-size: 12px;
  color: var(--primary-color);
  font-weight: bold;
}

/* 投资选项 */
.investment-options {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.options-list {
  display: flex;
  overflow-x: auto;
  gap: 10px;
  padding-bottom: 5px;
}

.option-item {
  min-width: 150px;
  flex-shrink: 0;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 12px;
  transition: all 0.3s;
}

.option-item.selected {
  border-color: var(--primary-color);
  background-color: rgba(11, 61, 145, 0.05);
}

.option-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.option-amount {
  font-size: 18px;
  font-weight: bold;
  color: #FF3B30;
}

.option-shares {
  font-size: 14px;
  color: #666;
}

.option-benefits {
  border-top: 1px dashed #f0f0f0;
  padding-top: 10px;
}

.benefit-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  margin-bottom: 5px;
  color: #666;
}

.benefit-item .van-icon {
  color: var(--primary-color);
  margin-right: 5px;
}

/* 产品描述 */
.product-description {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.description-content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 15px;
}

.product-features {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 12px;
}

.feature-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  margin-bottom: 8px;
}

.feature-item:last-child {
  margin-bottom: 0;
}

.feature-item .van-icon {
  color: var(--primary-color);
  margin-right: 8px;
}

/* 投资人评价 */
.reviews-section {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.reviews-list {
  background-color: white;
}

.review-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.review-avatar {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  margin-right: 10px;
}

.review-info {
  flex: 1;
}

.review-username {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 5px;
}

.review-rating .van-icon {
  font-size: 12px;
  margin-right: 2px;
}

.review-rating .van-icon.active {
  color: #FFD700;
}

.review-time {
  font-size: 12px;
  color: #999;
}

.review-content {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  align-items: center;
  background-color: white;
  padding: 10px 15px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
  z-index: 100;
}

.customer-service {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 15px;
  font-size: 12px;
  color: #666;
}

.customer-service .van-icon {
  font-size: 20px;
  margin-bottom: 3px;
}

.invest-btn {
  flex: 1;
  background-color: var(--primary-color);
  color: white;
  text-align: center;
  padding: 12px 0;
  border-radius: 25px;
  font-size: 16px;
  font-weight: bold;
}
</style>